//-----------------------------------------------------------------------------
// <copyright file="EmailHelper.cs" 
//            company="Rail Europe Limited">
//     Copyright (c) Rail Europe Limited. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace RailEurope.Cockpit
{
    #region Includes
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net.Mail;
    using System.Net.Mime;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Xml.Xsl;
    #endregion

    /// <summary>
    /// The IOUtilities class
    /// </summary>
    public static class EmailHelper
    {
        #region Public  Methods

        /// <summary>
        /// Sends the mail.
        /// </summary>
        /// <param name="to">The To recipient.</param>
        /// <param name="from">From (sender).</param>
        /// <param name="cc">The cc recipient.</param>
        /// <param name="bcc">The BCC recipient.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body of mail.</param>
        /// <param name="attachmentBody">The attachment body.</param>
        public static void SendMail(string to, string from, string cc, string bcc, string subject, string body, string attachmentBody)
        {
            SendMail(GetMail(to, from, cc, bcc, subject, body, attachmentBody));
        }

        /// <summary>
        /// Sends the mailMessage object to mailbox.
        /// </summary>
        /// <param name="mailMessage">The mail message.</param>
        public static void SendMail(MailMessage mailMessage)
        {
            //// Instantiate a new instance of SmtpClient
            SmtpClient mSmtpClient = new SmtpClient();
            ////mSmtpClient.Host = "192.168.130.17";
            //// Send the mail message
            mSmtpClient.Send(mailMessage);
        }

        /// <summary>
        /// Gets the mail.
        /// </summary>
        /// <param name="to">The To recipient.</param>
        /// <param name="from">From (sender).</param>
        /// <param name="cc">The cc recipient.</param>
        /// <param name="bcc">The BCC recipient.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body of mail.</param>
        /// <param name="attachmentBody">The attachment body.</param>
        /// <returns>The MailMessage</returns>
        public static MailMessage GetMail(string to, string from, string cc, string bcc, string subject, string body, string attachmentBody)
        {
            try
            {
                //// Instantiate a new instance of MailMessage
                MailMessage mMailMessage = new MailMessage();

                string mailFrom = from;
                //// Set the sender address of the mail message
                mMailMessage.From = new MailAddress(mailFrom);
                //// Set the recepient address of the mail message
                //// For Bulk Email
                if (!string.IsNullOrEmpty(to))
                {
                    if (to.Contains(";"))
                    {
                        char[] sep = { ';' };
                        string[] emailAddressArray = to.Split(sep);
                        foreach (string emailAddress in emailAddressArray)
                        {
                            if (!string.IsNullOrEmpty(emailAddress))
                            {
                                mMailMessage.To.Add(new MailAddress(emailAddress.Trim()));
                            }
                        }
                    }
                    else
                    {
                        mMailMessage.To.Add(new MailAddress(to));
                    }
                }
                //// For Bulk Email
                //// Check if the bcc value is null or an empty string
                if ((bcc != null) && (bcc.Length > 0))
                {
                    if (bcc.Contains(";"))
                    {
                        char[] sep = { ';' };
                        string[] emailAddressArray = bcc.Split(sep);
                        foreach (string emailAddress in emailAddressArray)
                        {
                            if (!string.IsNullOrEmpty(emailAddress))
                            {
                                if (IsValidEmailAddress(emailAddress.Trim()))
                                {
                                    mMailMessage.Bcc.Add(new MailAddress(emailAddress.Trim()));
                                }
                            }
                        }
                    }
                    else
                    {
                        //// Set the Bcc address of the mail message
                        if (IsValidEmailAddress(bcc))
                        {
                            mMailMessage.Bcc.Add(new MailAddress(bcc));
                        }
                    }
                }

                //// Check if the cc value is null or an empty value
                if ((cc != null) && (cc.Length > 0))
                {
                    if (cc.Contains(";"))
                    {
                        char[] sep = { ';' };
                        string[] emailAddressArray = cc.Split(sep);
                        foreach (string emailAddress in emailAddressArray)
                        {
                            if (!string.IsNullOrEmpty(emailAddress))
                            {
                                if (IsValidEmailAddress(emailAddress.Trim()))
                                {
                                    mMailMessage.CC.Add(new MailAddress(emailAddress.Trim()));
                                }
                            }
                        }
                    }
                    else
                    {
                        //// Set the CC address of the mail message
                        if (IsValidEmailAddress(cc))
                        {
                            mMailMessage.CC.Add(new MailAddress(cc));
                        }
                    }
                }

                //// Set the subject of the mail message
                mMailMessage.Subject = subject;
                //// Set the body of the mail message
                mMailMessage.Body = body;

                //// Set the format of the mail message body as HTML
                mMailMessage.IsBodyHtml = true;
                //// Set the priority of the mail message to normal
                mMailMessage.Priority = MailPriority.Normal;

                #region TextAttachment

                if (attachmentBody != null)
                {
                    MemoryStream memoryStream = new MemoryStream(System.Text.Encoding.GetEncoding(437).GetBytes(attachmentBody));
                    ContentType ct = new ContentType(MediaTypeNames.Text.Plain);
                    Attachment att = new Attachment(memoryStream, ct);
                    ContentDisposition disposition = att.ContentDisposition;
                    //// Suggest a file name for the attachment.
                    disposition.FileName = "emailtext.txt";
                    mMailMessage.Attachments.Add(att);
                }
                #endregion TextAttachment

                return mMailMessage;
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        #endregion

        #region Private Methods
        /// <summary>
        /// Determines whether [is valid email address] [the specified to check].
        /// </summary>
        /// <param name="toCheck">String to be validated.</param>
        /// <returns>
        ///    <c>true</c> if [is valid email address] [the specified to check]; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsValidEmailAddress(string toCheck)
        {
            ////Regex emailAddressPattern = new Regex(@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
            //// changed regex not to allow email ids of the format abc@def.co     fix for  bug#1166
            //// Regex emailAddressPattern = new Regex(@"^[A-Za-z0-9]([A-Za-z0-9_\-\.]*)@([A-Za-z0-9_\-\.]*)((\.[A-Za-z]{3}$)|(\.[A-Za-z]{2,3}(\.[A-Za-z]{2}){1,2}))$");

            ////string emailRegEx =@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            string emailRegEx = @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9_]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$";
            Regex emailAddressPattern = new Regex(emailRegEx);

            return emailAddressPattern.IsMatch(toCheck);
        }
        #endregion
    }
}
